package com.hogocloud.corelibrary.utils

import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.hogocloud.corelibrary.LibConfig

/**
 * 吐司工具
 */
object ToastUtils {

    private var mToast: Toast? = null
    private val mContext by lazy { LibConfig.getAppContext() }
    private val mHeight by lazy { (DeviceUtils.getScreenHeight(LibConfig.getAppContext()) * 0.2).toInt() }

    /**
     * 自定义图片toast
     *
     * @param resId   背景图片
     */
    fun showImage(resId: Int) {
        try {
            cancelToast()
            val imageView = ImageView(mContext)
            imageView.setBackgroundResource(resId)
            mToast = Toast(mContext)
            mToast?.setGravity(Gravity.CENTER, 0, -60)
            mToast?.view = imageView
            mToast?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 自定义布局toast
     *
     * @param layoutId
     */
    fun showLayout(layoutId: Int) {
        try {
            cancelToast()
            val view = View.inflate(mContext, layoutId, null)
            mToast = Toast(mContext)
            mToast?.setGravity(Gravity.CENTER, 0, -60)
            mToast?.view = view
            mToast?.duration = Toast.LENGTH_SHORT
            mToast?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 打印普通toast方法
     *
     * @param msg
     */
    @JvmOverloads
    fun showToast(msg: String, duration: Int = Toast.LENGTH_SHORT) {
        try {
            val toast = Toast.makeText(mContext, msg, duration)
            toast.setGravity(Gravity.BOTTOM, 0, mHeight)
            toast.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 打印普通toast方法
     *
     * @param resId
     */
    @JvmOverloads
    fun showToast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
        try {
            val toast = Toast.makeText(mContext, resId, duration)
            toast.setGravity(Gravity.BOTTOM, 0, mHeight)
            toast.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 关闭toast
     */
    fun cancelToast() {
        try {
            mToast?.cancel()
            mToast = null
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

}